(function($) {

    var bvd = function(dom) {
		var that = this;
		$.ready(function() {
			//获取视频元素
			that.video = document.querySelector(dom || 'video');
			//获取视频父元素
			that.vRoom = that.video.parentNode;
			//元素初始化
			that.initEm();
            //计算样式
    		that.initStyle();
			//事件初始化
			that.initEvent();
			//记录信息
			that.initInfo();
			//当前播放模式 false 为 mini播放
			that.isMax = false;
		})

		$.plusReady(function() {
			that.startWatchAcc();
		})

	}

	var pro = bvd.prototype;

	//记录信息
	pro.initInfo = function() {
		var that = this;
		//在onload状态下，offsetHeight才会获取到正确的值
		window.onload = function() {
			that.miniInfo = { //mini状态时的样式
				zIndex: 1,
				width: that.video.offsetWidth + 'px',
				height: that.video.offsetHeight + 'px',
				position: that.vRoom.style.position
			}

			that.maxInfo = { //max状态时的样式
				zIndex: 99,
				width: '100%',
				height: that.sw + 'px',
				position: 'fixed'
			}

		}

	}

	pro.initEm = function() {
		//初始化视频高度宽度
		var info = [
			document.documentElement.clientWidth || document.body.clientWidth,
			document.documentElement.clientHeight || document.body.clientHeigth
		];
		this.sw = info[0]; //屏幕宽
		this.sh = info[1]; //屏幕高
		var vh = (this.sw / 3 * 2); //视频高

		this.vRoom.style.width = (this.vW = this.sw) + 'px';
		this.vRoom.style.height = (this.vH = vh) + 'px';

		//先添加播放按钮
		this.vimg = document.createElement("img");
		this.vimg.src = '';
		this.vimg.className = 'vplay';
		this.vRoom.appendChild(this.vimg);

		//添加控制条
		this.vC = document.createElement("div");
		this.vC.classList.add('controls');
		this.vC.innerHTML = '<div><span class="current">00:00</span></div><div><div class="progressBar"><div class="timeBar"><div class="crr"></div></div></div></div><div><span class="duration">00:00</span></div><div><div class="fill"><img src=""/></div></div>';
		this.vRoom.appendChild(this.vC);

		//添加锁定按钮
		this.vlock = document.createElement("img");
		this.vlock.src = '';
		this.vlock.className = 'lock';
		this.vRoom.appendChild(this.vlock);
	}

	pro.initEvent = function() {
		var that = this;
		//给播放按钮图片添加事件
		this.vimg.addEventListener('tap', function() {
			that.video.play();
		})

		//获取到元数据
		this.eve('loadedmetadata', function() {
			that.vDuration = this.duration;
			that.vC.querySelector('.duration').innerHTML = stom(that.vDuration);
		});

		//视频播放事件
		this.eve('play', function() {
			that.vimg.style.display = 'none';
			that.vC.classList.add('vhidden');
			that.vCt = setTimeout(function() {
				that.vC.style.visibility = 'hidden';
			}, 4500);

			//新增Lock图标隐藏动画
			that.vlock.classList.add('lockhidden');
		})

		//视频播放中事件
		this.eve('timeupdate', function() {
			var currentPos = this.currentTime; //获取当前播放的位置
			//更新进度条
			var percentage = 100 * currentPos / that.vDuration;
			that.vC.querySelector('.timeBar').style.width = percentage + '%';
			//更新当前播放时间
			that.vC.querySelector('.current').innerHTML = stom(currentPos);
		});

		//视频点击暂停或播放事件
		this.eve('tap', function() {
			if(this.paused || this.ended) {
				//如果播放完毕，就重头开始播放
				this.ended && (this.currentTime = 0);
				this.play();
			} else {
				//播放时点击就暂停
				this.pause();
			}
		})

		//暂停or停止
		this.eve('pause', function() {
			that.vimg.style.display = 'block';
			that.vC.classList.remove('vhidden');
			that.vC.style.visibility = 'visible';
			that.vCt && clearTimeout(that.vCt);

			//新增Lock图标清除动画
			that.vlock.classList.remove('lockhidden');
		});

		//视频手势右滑动事件
		this.eve('swiperight', function() {
			that.setCurrentTime(5);
		});

		//视频手势左滑动事件
		this.eve('swipeleft', function() {
			that.setCurrentTime(-5);
		});

		//视频手势上滑动事件
		this.eve('swipeup', function() {
			//that.setVolume(0.2);
		});

		//视频手势下滑动事件
		this.eve('swipedown', function() {
			//that.setVolume(-0.2);
		});

		//全屏按钮点击事件
		this.vC.querySelector('.fill').addEventListener('tap', function() {
			//that.nativeMax();
			that.switch();
		});

		//全屏 时 锁定点击事件
		this.vlock.addEventListener('tap', function() {
			if(that.isLock) {
				that.unlockScreen();
				return;
			}
			that.lockScreen();
		});
        
        /**
         *2016-9-3 
         * 解决进度条拖动 在全屏和mini时的错位问题
         */
       var crr = this.vC.querySelector('.crr');
    	this.timeBar = that.vC.querySelector('.timeBar');
		crr.addEventListener('touchstart',function(e){
			//暂停播放
			that.video.pause();
		});
		
		crr.addEventListener('touchmove',function(e){
			//计算 手指x坐标 减去 进度条的x坐标
			var cha = e.touches[0].pageX - that.vCstyle.barLX;
			if(cha<0){
				cha = 0;
			}else if(cha>that.vCstyle.barW){
				cha = that.vCstyle.barW;
			}
			//计算移动的x距离百分比
			that.bl = 100 * cha / that.vCstyle.barW;
			that.timeBar.style.width = that.bl + '%';
		});
		
		crr.addEventListener('touchend',function(e){
			//跳转到百分比的视频进度
			that.video.currentTime = that.video.duration * that.bl / 100;
			//继续播放
			that.video.play();
		});
        
        
		this.oback = $.back;
		//监听安卓返回键
		$.back = function(){
			if(that.isMax){
				if(!that.isLock){
					setTimeout(function(){
						that.startWatchAcc();
					},1000);
					that.clearWatchAcc();
					that.switch();
				}
				return;
			}
			that.oback();
		}
	}
    
    pro.initStyle = function(){
    	 
		var	bar = this.vC.querySelector('.progressBar'),
			barW = bar.offsetWidth,
			barLX = bar.offsetLeft,
			barRX = barLX+barW;
		this.vCstyle = {
			barW : barW,
			barLX : barLX,
			barRx : barRX
		}; 
		console.log(JSON.stringify(this.vCstyle))
	}

	pro.setIsMax = function(state) {
		this.isMax = !state;
		this.switch();
	}
	pro.getIsMax = function() {
		return this.isMax;
	}

	//全屏 mini 两种模式切换
	pro.switch = function() {
		var vR = this.vRoom;
		//获取需要转换的样式信息
		var info = this.isMax ? this.miniInfo : this.maxInfo;
		this.isMax = !this.isMax;

		setTimeout(function() {
    		for(var i in info) {
				vR.style[i] = info[i];
			}
			//重新计算视频宽度和进度条的左边距
			this.initStyle();
		}.bind(this), 500);

		plus.navigator.setFullscreen(this.isMax);
		if(this.isMax) {
			//自感应横屏方向状态
			plus.screen.lockOrientation("landscape"); //-primary");
		} else {
			//锁定手机正竖直方向
			plus.screen.lockOrientation("portrait-primary");
		}

		//全屏时 显示锁定 图标
		this.vlock.style.visibility = this.isMax ? 'visible' : 'hidden';

	}

	//锁定屏幕
	pro.lockScreen = function() {
		$.toast('锁定屏幕');
		var that = this;
		//更换video点击事件为 显示 lock图标，并保存 video之前的事件 
		this.videoTapFn = this.eve('tap', function() {
			that.lockT = setTimeout(function(){
				that.vlock.classList.add('lockhidden');
			},500);
				//重新开始播放样式
			that.vlock.classList.remove('lockhidden');
			that.vlock.style.visibility = 'visible';
			//that.vlock.classList.add('lockhidden');
		}, true);
		//隐藏控制条
		this.vC.style.visibility = 'hidden';
		//给Lock图标增加 隐藏样式类
		this.vlock.classList.add('lockhidden');
		//锁定屏幕时，不监控重力感应
		this.clearWatchAcc();
		//标识当前更改的Lock状态
		this.isLock = true;

	}

	//解锁屏幕
	pro.unlockScreen = function() {
		$.toast('解锁屏幕');
		//替换回video之前的点击事件
		this.eve('tap', this.videoTapFn, true);
		
		//给Lock图标清楚 隐藏样式类
		this.vlock.classList.remove('lockhidden');
		//不锁定屏幕时，监控重力感应
		this.startWatchAcc();
		//标识当前更改的Lock状态
		this.isLock = false;
	}

	//开启方向感应
	pro.startWatchAcc = function() {
			var that = this;
			this.watchAccFun = plus.accelerometer.watchAcceleration(function(a) {
				if(that.getIsMax()) {
					//当前为全屏状态
					//判断是否满足竖屏Mini状态
					a.yAxis >= 5 && that.setIsMax(false);
				} else {
					//当前为Mini状态
					//判断是否满足全屏Max状态
					Math.abs(a.xAxis) >= 5 && that.setIsMax(true);
				}
			}, function(e) {
				//出错了大不了 不自动旋转呗  让它手动 切换
				console.log("Acceleration error: " + e.message);
				that.clearWatchAcc();
			}, {
				frequency: 1200
			});
		}
		//关闭方向感应
	pro.clearWatchAcc = function() {
		this.watchAccFun && plus.accelerometer.clearWatch(this.watchAccFun);
	}

	//使用原生支持的方式播放
	pro.nativeMax = function() {
		if(!window.plus) {
			//非html5+环境
			return;
		}
		if($.os.ios) {
			console.log('ios')
			this.video.removeAttribute('webkit-playsinline');
		} else if($.os.android) {
			console.log('android');
			var url = this.video.querySelector('source').src;
			var Intent = plus.android.importClass("android.content.Intent");
			var Uri = plus.android.importClass("android.net.Uri");
			var main = plus.android.runtimeMainActivity();
			var intent = new Intent(Intent.ACTION_VIEW);
			var uri = Uri.parse(url);
			intent.setDataAndType(uri, "video/*");
			main.startActivity(intent);
		}
	}

	//跳转视频进度 单位 秒
	pro.setCurrentTime = function(t) {
			this.video.currentTime += t;
		}
		//设置音量大小 单位 百分比 如 0.1
	pro.setVolume = function(v) {
			v = this.video.volume + v;
			if(v < 0) v = 0;
			else if(v > 1) v = 1;
			this.video.volume = v;
		}
		//设置屏幕亮度  单位 百分比 如 0.1
	pro.setBrightness = function(b) {
			b = plus.screen.getBrightness() + v;
			if(b < 0) b = 0;
			else if(b > 1) b = 1;
			plus.screen.setBrightness(b);
		}
		//切换播放地址 
	pro.setUrl = function(nUrl) {
		var v = this.video;
		var source = v.querySelector('source');
		source.src = v.src = nUrl;
		source.type = 'video/' + nUrl.split('.').pop();
		v.play();
	}

	var events = {};

	//增加 或者删除事件    isBack 是否返回  这次添加事件时 被删除 的上一个 事件
	pro.eve = function(ename, callback, isBack) {
		var fn;
		if(callback && typeof(callback) == 'function') {
			isBack && (fn = arguments.callee.call(this, ename));
			events[ename] = callback;
			this.video.addEventListener(ename, events[ename]);
			console.log('添加事件：' + ename);
		} else {
			fn = events[ename];
			fn && this.video.removeEventListener(ename, fn);
			console.log('删除事件：' + ename);
		}

		return fn;
	}

	function stom(t) {
		var m = Math.floor(t / 60);
		m < 10 && (m = '0' + m);
		return m + ":" + (t % 60 / 100).toFixed(2).slice(-2);
	}

	var nv = null;
	$.bvd = function(dom) {
		return nv || (nv = new bvd(dom));
	}
}(mui))